package usf.gwt.ui.bootstrap.client;

import usf.gwt.ui.bootstrap.client.core.BootstrapContainer;
import usf.gwt.ui.bootstrap.client.core.Constants;
import usf.gwt.ui.bootstrap.client.core.JqueryUtils;
import usf.gwt.ui.bootstrap.client.core.StyleEnum.HasType;
import usf.gwt.ui.bootstrap.client.event.SubmitFormEvent;
import usf.gwt.ui.bootstrap.client.event.SubmitFormEvent.HasSubmitFormHandler;
import usf.gwt.ui.bootstrap.client.event.SubmitFormEvent.SubmitFormHandler;

import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.event.shared.HandlerRegistration;

public class Form extends BootstrapContainer implements HasType<FormType>, HasSubmitFormHandler {
	
	public Form() {
		super();
		onSubmit(this);
	}

	@Override
    protected Element initWidget() {
        Element form = Document.get().createFormElement();
        form.setAttribute(Constants.ATTRIB_ROLE, Constants.ATTRIB_FORM);
        return form;
    }

	@Override
    public void setType(FormType type) {
    	JqueryUtils.switchClass(getElement(), FormType.values(), type);
    }
	
	@Override
	public FormType getType() {
		return (FormType) JqueryUtils.hasClass(getElement(), FormType.values());
	}
    
    @Override
    public HandlerRegistration addSubmitFormHandler(SubmitFormHandler handler) {
    	return addHandler(handler, SubmitFormEvent.type);
    }
    protected void fireFormSubmit(){
    	fireEvent(new SubmitFormEvent());
    }
    
    protected static final native void onSubmit(final Form f) /*-{
    	$wnd.$(f.@usf.gwt.ui.bootstrap.client.Form::getElement()()).submit(function(e) {
    		e.preventDefault();
    		f.@usf.gwt.ui.bootstrap.client.Form::fireFormSubmit()();
    	});
    }-*/;
    
}
